package demo16_3;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;

//用队列实现栈
public class MyStack {
    private Queue<Integer> queue1;
    private Queue<Integer> queue2;

    public MyStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }

    public void push(int x) {
        //入到不为空的队列
        if (!queue1.isEmpty()) {
            queue1.offer(x);
        }else if (!queue2.isEmpty()){
            queue2.offer(x);
        }else {
            //如果两个队列都为空
            queue1.offer(x);
        }
    }

    public int pop() {
        if (empty()) {
            return -1;
        }
        //出不为空的队列
        if (!queue1.isEmpty()){
            //出size-1个放到queue2中
            int size = queue1.size();
            for (int i = 0; i < size - 1; i++) {
                int temp = queue1.poll();
                queue2.offer(temp);
            }
            return queue1.poll();
        }else {
            int size = queue2.size();
            for (int i = 0; i < size - 1; i++) {
                int temp = queue2.poll();
                queue1.offer(temp);
            }
            return queue2.poll();
        }
    }

    public int top() {
        if(empty()) {
            return -1;
        }
        //出不为空的队列
        int temp = -1;
        if (!queue1.isEmpty()){
            //出size-1个放到queue2中
            int size = queue1.size();
            for (int i = 0; i < size; i++) {
                temp = queue1.poll();
                queue2.offer(temp);
            }
        }else {
            int size = queue2.size();
            for (int i = 0; i < size; i++) {
                temp = queue2.poll();
                queue1.offer(temp);
            }
        }
        return temp;
    }

    public boolean empty() {
        //两个队列都为空
        return queue1.isEmpty() && queue2.isEmpty();
    }
}
